<template>
  <div class="barcode-management">
    <!-- 搜索区域 -->
    <div class="search-card" v-show="showSearch">
      <el-form :inline="true" :model="searchForm" class="search-form" ref="searchFormRef">
        <el-form-item label="条码类型">
          <el-select v-model="searchForm.barcodeType" placeholder="请选择条码类型" clearable style="width: 200px;">
            <el-option
              v-for="item in barcodeTypes"
              :key="item.key"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务编码">
          <el-input v-model="searchForm.businessCode" placeholder="请输入业务编码" clearable />
        </el-form-item>
        <el-form-item label="业务名称">
          <el-input v-model="searchForm.businessName" placeholder="请输入业务名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left">
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增条码
        </el-button>
      </div>
      <div class="right">
        <el-tooltip content="隐藏查询" placement="top">
          <el-button circle @click="toggleSearch">
            <el-icon><Hide /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="刷新数据" placement="top">
          <el-button circle @click="refreshData">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="barcodeList"
        border
        style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="条码" width="180" align="center">
          <template #default="scope">
            <div class="barcode-wrapper">
              <img :src="generateBarcodeUrl(scope.row.barcodeFormat, scope.row.barcode)" 
                   :alt="scope.row.barcode" 
                   class="barcode-image" />
              <el-button type="primary" link @click="downloadBarcode(scope.row)">
                <el-icon><Download /></el-icon>下载
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="barcodeFormat" label="条码格式" width="120" />
        <el-table-column prop="barcodeType" label="条码类型" width="120" />
        <el-table-column prop="barcodeDesc" label="条码描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="businessCode" label="业务编码" width="120" />
        <el-table-column prop="businessName" label="业务名称" width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="是否生效" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'info'" effect="plain">
              {{ scope.row.status ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增条码' : '编辑条码'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-height: 60vh; overflow-y: auto;"
      >
        <el-form-item label="条码" prop="barcode">
          <el-input v-model="form.barcode" placeholder="请输入条码" />
        </el-form-item>
        <el-form-item label="条码格式" prop="barcodeFormat">
          <el-select v-model="form.barcodeFormat" placeholder="请选择条码格式" style="width: 100%">
            <el-option label="QR二维码" value="QR二维码" />
            <el-option label="条形码" value="条形码" />
          </el-select>
        </el-form-item>
        <el-form-item label="条码类型" prop="barcodeType">
          <el-select v-model="form.barcodeType" placeholder="请选择条码类型" style="width: 100%">
            <el-option
              v-for="item in barcodeTypes"
              :key="item.key"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="条码描述" prop="barcodeDesc">
          <el-input v-model="form.barcodeDesc" placeholder="请输入条码描述" />
        </el-form-item>
        <el-form-item label="业务编码" prop="businessCode">
          <el-input v-model="form.businessCode" placeholder="请输入业务编码" />
        </el-form-item>
        <el-form-item label="业务名称" prop="businessName">
          <el-input v-model="form.businessName" placeholder="请输入业务名称" />
        </el-form-item>
        <el-form-item label="是否生效" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Hide, Download } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

// 控制搜索区域显示
const showSearch = ref(true)

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  barcodeType: '',
  businessCode: '',
  businessName: ''
})

// 条码类型选项
const barcodeTypes = ref([
  { key: 'qr', value: 'QR码' },
  { key: 'bar', value: '条形码' }
])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表格数据
const barcodeList = ref([])

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')

// 表单数据
interface BarcodeForm {
  id: number;
  barcode: string;
  barcodeFormat: string;
  barcodeType: string;
  barcodeDesc: string;
  businessCode: string;
  businessName: string;
  status: number;
  barcodeImage?: string;
}

const formRef = ref<FormInstance>()
const form = reactive<BarcodeForm>({
  id: 0,
  barcode: '',
  barcodeFormat: '',
  barcodeType: '',
  barcodeDesc: '',
  businessCode: '',
  businessName: '',
  status: 1,
  barcodeImage: ''
})

// 表单验证规则
const rules = {
  barcode: [{ required: true, message: '请输入条码', trigger: 'blur' }],
  barcodeFormat: [{ required: true, message: '请选择条码格式', trigger: 'change' }],
  barcodeType: [{ required: true, message: '请选择条码类型', trigger: 'change' }],
  businessCode: [{ required: true, message: '请输入业务编码', trigger: 'blur' }],
  businessName: [{ required: true, message: '请输入业务名称', trigger: 'blur' }]
}

// 初始化
onMounted(() => {
  getBarcodeTypes()
  loadData()
})

// 获取条码类型列表
const getBarcodeTypes = async () => {
  try {
    const response = await axios.get('/api/warehouses/getBarcodeTypes')
    if (response.data.success) {
      barcodeTypes.value = response.data.data
    }
  } catch (error) {
    console.error('获取条码类型失败:', error)
    ElMessage.error('获取条码类型失败')
  }
}

// 加载表格数据
const loadData = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/warehouses/getBarcodeList', {
      params: {
        ...searchForm,
        pageIndex: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.success) {
      barcodeList.value = response.data.data
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.barcodeType = ''
  searchForm.businessCode = ''
  searchForm.businessName = ''
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  loadData()
}

// 切换搜索区域显示
const toggleSearch = () => {
  showSearch.value = !showSearch.value
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, {
    id: 0,
    barcode: '',
    barcodeFormat: '',
    barcodeType: '',
    barcodeDesc: '',
    businessCode: '',
    businessName: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认要删除该条码吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用删除接口
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 监听条码格式和条码内容变化，预览条码图片
watch([() => form.barcodeFormat, () => form.barcode], async ([newFormat, newBarcode]) => {
  if (newFormat && newBarcode) {
    try {
      form.barcodeImage = await generateBarcodeUrl(newFormat, newBarcode)
    } catch (error) {
      console.error('生成条码预览失败:', error)
    }
  }
})

// 生成条码图片URL
const generateBarcodeUrl = (format: string, content: string) => {
  if (!content) return ''
  
  const timestamp = new Date().getTime() // 添加时间戳避免缓存
  
  if (format === 'QR二维码') {
    // 使用QR Code API
    return `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(content)}&t=${timestamp}`
  } else if (format === '条形码') {
    // 使用 TEC-IT Barcode API
    return `https://barcode.tec-it.com/barcode.ashx?data=${encodeURIComponent(content)}&code=Code128&multiplebarcodes=false&translate-esc=true&unit=Fit&dpi=96&imagetype=Png&rotation=0&color=%23000000&bgcolor=%23ffffff&codepage=Default&qunit=Mm&quiet=0&hidehrt=False&t=${timestamp}`
  }
  return ''
}

// 下载条码图片
const downloadBarcode = async (row: any) => {
  try {
    // 创建一个临时的img元素来加载条码图片
    const img = new Image()
    img.crossOrigin = 'anonymous' // 允许跨域
    img.src = generateBarcodeUrl(row.barcodeFormat, row.barcode)
    
    img.onload = () => {
      // 创建canvas
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      if (!ctx) return

      // 绘制图片到canvas
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(img, 0, 0)

      // 转换为blob并下载
      canvas.toBlob((blob) => {
        if (!blob) {
          ElMessage.error('生成图片失败')
          return
        }
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${row.barcode}.png`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      }, 'image/png')
    }

    img.onerror = () => {
      ElMessage.error('图片加载失败')
    }
  } catch (error) {
    console.error('下载条码失败:', error)
    ElMessage.error('下载条码失败')
  }
}

// 修改提交表单方法
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.put('/api/warehouses/updateBarcode', form)
        if (response.data.success) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
          dialogVisible.value = false
          loadData()
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}
</script>

<style scoped>
.barcode-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.search-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
}

:deep(.el-button--link) {
  padding: 0 4px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.barcode-wrapper {
  padding: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.barcode-image {
  max-width: 150px;
  max-height: 150px;
  object-fit: contain;
}
</style>